package edu.metrostate.capstonediner;

import java.util.ArrayList;

import android.content.Intent;

public class HighScoreScreen {
	private final float DONE_BUTTON_Y = 0.125f * Constants.SCREEN_WIDTH;
	
	private Background background;
	
	private GameText doneText;
	private GameButton doneButton;
	private ArrayList<GameText> highScoreText;
	
	private GameRenderer renderer;
	private GameInput input;
	private GameActivity activity;
	
	boolean isDisplayed;
	
	public HighScoreScreen(GameActivity activity, GameInput input) {
		background = new Background();
		doneText = new GameText("Return to Main Menu", 68, DONE_BUTTON_Y + 0.5f * Constants.DEFAULT_FONT_SIZE, Constants.TEXT_LAYER, Constants.DEFAULT_FONT_SIZE, Constants.DEFAULT_FONT);
		doneButton = new GameButton(DONE_BUTTON_Y);
		
		highScoreText = new ArrayList<GameText>(Constants.NUMBER_HIGH_SCORE_DISPLAYED + 1);
		
		this.renderer = activity.getRenderer();
		this.input = input;
		this.activity = activity;
	}
	
	public void show() {
		ArrayList<String> highScoreList;
		float yPosition = 2.0f * DONE_BUTTON_Y + doneButton.getHeight(); 
		
		// Remove comment once database connection is established
		highScoreList = DatabaseHTTP.getHighScoreList();
		
		renderer.add(background);
		renderer.add(doneText);
		renderer.add(doneButton);
		
		highScoreText.add(new GameText("High Scores:", 30, yPosition, Constants.TEXT_LAYER, Constants.DEFAULT_FONT_SIZE, Constants.FONT2));
		yPosition += Constants.DEFAULT_FONT_SIZE;
		
		for (String s : highScoreList) {
			highScoreText.add(new GameText(s, 30, yPosition, Constants.TEXT_LAYER, Constants.DEFAULT_FONT_SIZE - 3, Constants.FONT2));
			yPosition += Constants.DEFAULT_FONT_SIZE;
		}
		
		for (GameText t : highScoreText) {
			renderer.add(t);
		}
		
		renderer.update();
		
		isDisplayed = true;
		while (isDisplayed) {
			try {
				Thread.sleep(0);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			parseInput();
		}
	}
	
	private void hide() {
		isDisplayed = false;
		
		renderer.remove(background);
		renderer.remove(doneText);
		renderer.remove(doneButton);
		
		for (GameText t : highScoreText) {
			renderer.remove(t);
		}
	}
	
	private void parseInput() {
		if(input.getX() < Constants.SCREEN_WIDTH - 32f) {
			// Done
			if (input.getY() > DONE_BUTTON_Y && input.getY() < DONE_BUTTON_Y + doneButton.getHeight()) {
				hide();
				
				//Intent i = new Intent(activity.getApplicationContext(), MainMenu.class);
				activity.finish();
				//activity.startActivity(i);
			}
		}
	}
}
